import $api from './api.js';
export default {
	/**
	 * 显示消息提示框
	 *  @param {Object} params 参数
	 */
	showToast(params = {}) {
		params.title = params.title || "";
		params.icon = params.icon || "none";
		params.duration = params.duration || 1500;
		uni.showToast(params);
		if (params.success) params.success();
	},
	loginTo(to, param, mode) {
		if (!uni.getStorageSync('batoken')) {
			this.redirectTo('/PDA/pages/login/login')
		} else {
			this.redirectTo(to, param, mode)
		}
	},

	getCode(url) {
		if (url.indexOf('https://jy.hhljy.com') === 0) {
			const parts = url.split("XXX/");
			if (parts.length > 1) {
				return ['b', parts[1]];
			}
		}
		const t = this.getQueryString(url, 't');
		if (t == 'b') {
			return ['b', this.getQueryString(url, 'p') ? this.getQueryString(url, 'p') : this.getQueryString(url, 'c')];
		} else if (t == 'm') {
			return ['m', this.getQueryString(url, 'p')];
		} else if (t == 's') {
			return ['s', this.getQueryString(url, 'p')];
		}
		return [null, null];
	},

	getQueryString(uri, name) {
		if (!uri) {
			return null;
		}
		try {
			let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			let url = uri.split('?')[1].match(reg);
			if (url != null) {
				return decodeURI(url[2]) //decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。
			} else {
				return null
			}
		} catch (e) {
			return null
		}
	},

	// 预览图片
	previewImage(urls, index = 0) {
		const urlList = Array.isArray(urls) ? urls : [urls];
		uni.previewImage({
			urls: urlList,
			current: index,
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
				success: function(data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		});
	},
	copyText(text) {
		uni.setClipboardData({
			data: text,
			success: function() {
				uni.showToast({
					title: '复制成功',
					icon: 'success',
					duration: 2000
				});
			}
		});
	},


	/**
	 * 页面跳转
	 * @param {string} to 跳转链接 /pages/index/index
	 * @param {Object} param 参数 {key : value, ...}
	 * @param {string} mode 模式
	 */
	redirectTo(to, param, mode) {
		let url = to;
		let tabbarList = [];
		if (param != undefined) {
			Object.keys(param).forEach(function(key) {
				if (url.indexOf('?') != -1) {
					url += "&" + key + "=" + param[key];
				} else {
					url += "?" + key + "=" + param[key];
				}
			});
		}
		for (let i = 0; i < tabbarList.length; i++) {
			if (url.indexOf(tabbarList[i]) == 0) {
				uni.switchTab({
					url
				});
				return;
			}
		}
		switch (mode) {
			case 'tabbar':
				// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
				uni.switchTab({
					url
				});
				break;
			case 'redirectTo':
				// 关闭当前页面，跳转到应用内的某个页面。
				uni.redirectTo({
					url
				});
				break;
			case 'reLaunch':
				// 关闭所有页面，打开到应用内的某个页面。
				uni.reLaunch({
					url
				});
				break;
			default:
				// 保留当前页面，跳转到应用内的某个页面
				uni.navigateTo({
					url
				});
		}
	},

	// debounce 函数示例
	debounce: function(func, wait, immediate) {
		let timeout;

		return function(...args) {
			const context = this;
			const callNow = immediate && !timeout;

			clearTimeout(timeout);
			timeout = setTimeout(() => {
				timeout = null;
				if (!immediate) func.apply(context, args);
			}, wait);

			if (callNow) func.apply(context, args);
		};
	},

	htmlPic(html) {
		let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
			match = match
				.replace(/style="[^"]+"/gi, "")
				.replace(/style='[^']+'/gi, "");
			match = match
				.replace(/width="[^"]+"/gi, "")
				.replace(/width='[^']+'/gi, "");
			match = match
				.replace(/height="[^"]+"/gi, "")
				.replace(/height='[^']+'/gi, "");
			return match;
		});
		newContent = newContent.replace(
			/style="[^"]+"/gi,
			function(match, capture) {
				match = match
					.replace(/width:[^;]+;/gi, "max-width:100%;")
					.replace(/width:[^;]+;/gi, "max-width:100%;");
				return match;
			}
		);

		// newContent = newContent.replace(/<br[^>]*\/>/gi, '');
		var msContentWeb = newContent.replace(
			/\<img/gi,
			'<img style="max-width:100%;height:auto;display:inline-block;"'
		);
		msContentWeb = msContentWeb.replace('style=""', "")
		return msContentWeb;
	},
	copyText(text) {
		uni.setClipboardData({
			data: text,
			success: function() {
				uni.showToast({
					title: '复制成功',
					icon: 'success',
					duration: 2000
				});
			}
		});
	},
	async checkMemberLogin() {
		const result = await $api.sendRequest({
			url: 'auth/islogin',
			data: {
				url: window.location.href
			}
		})
		if (result.code == 401) {
			// #ifdef H5
			window.location.href = result.data.url;
			// #endif
			return false;
		}
		return true;
	}
}